package com.example.liuke.guangguang.untils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Created by liuke on 2018/5/8.
 */

public class InetAddressExample {
    public static void main(String[] args){

        try {
            //得到网络接口和关联这个主机的地址
            Enumeration<NetworkInterface> interfaceList = NetworkInterface.getNetworkInterfaces();
            if(interfaceList == null) {
                System.out.println("------没有接口发现----");
            } else {
                int count=1;
                //遍历得到接口
                while (interfaceList.hasMoreElements()) {
                    NetworkInterface iface = interfaceList.nextElement();
                    //打印接口的名字
                    System.out.println("接口"+(count++)+"的名称为：" + iface.getName());
                    //获取地址
                    Enumeration<InetAddress> addrList = iface.getInetAddresses();
                    if(!addrList.hasMoreElements()) {
                        //打印对于这个接口没有地址
                        System.out.println("对于这个接口没有地址");
                    } else {
                        while (addrList.hasMoreElements()) {
                            InetAddress address = addrList.nextElement();
                            System.out.println("这个地址是：" +(address instanceof Inet4Address ? "(v4)"
                                    :(address instanceof Inet6Address ? "(v6)" :"未知")));
                            System.out.println(": " + address.getHostAddress());
                        }
                    }

                }
            }
        } catch (SocketException e) {
            System.out.println("得到网络接口异常");
            e.printStackTrace();
        }
        //从给入参数获取名称或者地址
        for (String host : args){
            System.out.println(host + ":");
            try {
                InetAddress[] addressList = InetAddress.getAllByName(host);
                for (InetAddress address : addressList) {
                    System.out.println("\t" + address.getHostName()
                            + "/" + address.getHostAddress());
                }
            } catch (UnknownHostException e) {
                System.out.println("不能找到对应的地址：" + host);
                e.printStackTrace();
            }

        }
    }
}

